package com.caiden_micheal.user.service.impl;

import com.alibaba.fastjson2.JSON;
import com.caiden_micheal.base.constant.LoggerHead;
import com.caiden_micheal.base.domain.AjxResult;
import com.caiden_micheal.base.dto.PageDTO;
import com.caiden_micheal.base.properties.AESProperties;
import com.caiden_micheal.base.properties.JWTProperties;
import com.caiden_micheal.base.utils.*;
import com.caiden_micheal.base.vo.PageVo;
import com.caiden_micheal.menu.service.MenuService;
import com.caiden_micheal.menu.utils.MenuUtil;
import com.caiden_micheal.org.domain.Org;
import com.caiden_micheal.org.mapper.OrgMapper;
import com.caiden_micheal.permission.domain.Permission;
import com.caiden_micheal.permission.mapper.PermissionMapper;
import com.caiden_micheal.position.service.PositionService;
import com.caiden_micheal.user.domain.PositionOrgUser;
import com.caiden_micheal.user.domain.User;
import com.caiden_micheal.user.domain.UserAuthority;
import com.caiden_micheal.user.dto.DecryptDataDTO;
import com.caiden_micheal.user.mapper.PositionOrgUserMapper;
import com.caiden_micheal.user.mapper.UserAuthorityMapper;
import com.caiden_micheal.user.mapper.UserMapper;
import com.caiden_micheal.org.service.OrgService;
import com.caiden_micheal.user.service.UserService;
import com.caiden_micheal.user.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAuthorityMapper userAuthorityMapper;
    @Autowired
    private JWTProperties jwtProperties;
    @Autowired
    private PositionService positionService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private PositionOrgUserMapper positionOrgUserMapper;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private AESProperties aesProperties;
    @Lazy
    @Autowired
    private MenuService menuService;

    @Override
    public User findByUserName(String username) {
        User user = new User();
        user.setUsername(username);
        return userMapper.findOne(user);
    }

    @Override
    public User findByUserId(Long id) {
        User user = new User();
        user.setId(id);
        return userMapper.findOne(user);
    }

    @Override
    public User findByEmail(String email) {
        User user = new User();
        user.setEmail(email);
        return userMapper.findOne(user);
    }

    @Override
    public void registerUser(RegisterVO registerVO) {
        userMapper.saveUser(registerVO);
    }

    @Override
    public Integer validEmailAndUserNameRepeat(String username, String email) {
        User byUserName = findByUserName(username);
        if (byUserName != null) return 1;
        User byEmail = findByEmail(email);
        if (byEmail != null) return 2;
        return 0;
    }

    @Override
    public void activeUsreById(Long id) {
        User user = new User();
        user.setId(id);
        user.setDisabled(0);
        userMapper.updateUser(user);
    }

    @Override
    public void delUserById(Long id) {
        // TODO 删除相关信息
        User user = new User();
        user.setId(id);
        userMapper.deleteUser(user);
    }

    @Override
    public List<String> findUserAuthorityNameListByUserId(Long id, Boolean forcedRefresh) {
        String authorityNamekey = "caiden_micheal:user:" + id + ":authorityName";
        if (!forcedRefresh) {
            String value = RedisUtil.getValue(authorityNamekey);
            if (!StringUtils.isEmpty(value)) {
                String[] split = value.split(",");
                return Arrays.asList(split);
            }
        }
        List<String> authorityNameList = new ArrayList<>();
        queryDataAndFillList(id, authorityNameList);
        RedisUtil.setKey(authorityNamekey, String.join(",", authorityNameList));
        RedisUtil.expireKey(authorityNamekey, jwtProperties.getExpirationTime());
        return authorityNameList;
    }

    @Override
    public void userOnlineStatusSet(Long id, String flag) {
        String onlineStatusKey = "caiden_micheal:user:" + id + ":onlineStatus";
        RedisUtil.setKey(onlineStatusKey, flag);
        RedisUtil.expireKey(onlineStatusKey, jwtProperties.getExpirationTime());
    }

    @Override
    public PageDTO findUsersByCondition(UserQueryVO userQueryVO) {
        PageVo page = userQueryVO.getPage();
        if (page == null) {
            logger.warn(LoggerHead.warnHead() + "userQueryVO.page is Null!");
            return null;
        }
        page.setCurrentIndex((long) (page.getCurrentPage() - 1) * page.getPageSize());
        List<User> userList = userMapper.findDesensitizationListPaginationQuery(userQueryVO);
        page.setCount(userMapper.findDesensitizationListQueryCount(userQueryVO));
        return new PageDTO(userList, page);
    }

    @Override
    public PageDTO findUsersByExcludePositionCondition(UserQueryVO userQueryVO) {
        PageVo page = userQueryVO.getPage();
        if (page == null) {
            logger.warn(LoggerHead.warnHead() + "userQueryVO.page is Null!");
            return null;
        }
        page.setCurrentIndex((long) (page.getCurrentPage() - 1) * page.getPageSize());
        List<PositionOrgUser> positionUserOrgList = positionOrgUserMapper.findByPositionId(userQueryVO.getPositionId());
        if (positionUserOrgList.size() == 0) {
            positionUserOrgList = null;
        }
        List<User> userList = userMapper.findExcludePositionDesensitizationListPaginationQuery(userQueryVO, positionUserOrgList);
        page.setCount(userMapper.findExcludePositionDesensitizationListPaginationQueryCount(userQueryVO, positionUserOrgList));
        return new PageDTO(userList, page);
    }

    @Override
    public PageDTO findUsersByPositionCondition(UserQueryVO userQueryVO) {
        PageVo page = userQueryVO.getPage();
        if (page == null) {
            logger.warn(LoggerHead.warnHead() + "userQueryVO.page is Null!");
            return null;
        }
        page.setCurrentIndex((long) (page.getCurrentPage() - 1) * page.getPageSize());
        List<User> userList = positionOrgUserMapper.findByPositionIdLinkUserCondition(userQueryVO, page);
        page.setCount(positionOrgUserMapper.findByPositionIdLinkUserConditionCount(userQueryVO, page));
        return new PageDTO(userList, page);
    }

    @Override
    public PageDTO findUsersByConditionPermission(UserQueryVO userQueryVO) {
        PageVo page = userQueryVO.getPage();
        if (page == null) {
            logger.warn(LoggerHead.warnHead() + "userQueryVO.page is Null!");
            return null;
        }
        List<UserAuthority> userAuthorityList = userAuthorityMapper.findByAuthorityId(userQueryVO.getPermissionId());
        if (userAuthorityList == null || userAuthorityList.size() == 0) {
            return null;
        }
        page.setCurrentIndex((long) (page.getCurrentPage() - 1) * page.getPageSize());
        List<User> userList = userMapper.findByPermissionConditionDesensitizationListPaginationQuery(userAuthorityList, userQueryVO);
        page.setCount(userMapper.findByPermissionConditionDesensitizationListPaginationQueryCount(userAuthorityList, userQueryVO));
        return new PageDTO(userList, page);
    }

    @Override
    public PageDTO findUsersExcludeConditionPermission(UserQueryVO userQueryVO) {
        PageVo page = userQueryVO.getPage();
        if (page == null) {
            logger.warn(LoggerHead.warnHead() + "userQueryVO.page is Null!");
            return null;
        }
        List<UserAuthority> userAuthorityList = userAuthorityMapper.findByAuthorityId(userQueryVO.getPermissionId());
        if (userAuthorityList.size() == 0) {
            userAuthorityList = null;
        }
        page.setCurrentIndex((long) (page.getCurrentPage() - 1) * page.getPageSize());
        List<User> userList = userMapper.findExcludePermissionConditionDesensitizationListPaginationQuery(userAuthorityList, userQueryVO);
        page.setCount(userMapper.findExcludePermissionConditionDesensitizationListPaginationQueryCount(userAuthorityList, userQueryVO));
        return new PageDTO(userList, page);
    }

    @Transactional
    @Override
    public AjxResult addUserPermission(AddUserPermissionVO addUserPermissionVO) {
        if (addUserPermissionVO == null || addUserPermissionVO.getUserIds() == null || addUserPermissionVO.getAuthorityId() == null) {
            return AjxResult.paramError("参数传入错误");
        }
        List<User> userList = userMapper.findUserListByIds(addUserPermissionVO.getUserIds());
        if (userList.size() == 0) {
            return AjxResult.paramError("传入的用户均不存在");
        }
        Permission permission = permissionMapper.findById(addUserPermissionVO.getAuthorityId());
        if (permission == null) {
            return AjxResult.paramError("权限不存在");
        }
        try {
            ArrayList<Permission> permissionList = new ArrayList<>();
            permissionList.add(permission);
            MenuUtil.permissionListMerging(permissionList, menuService);
            for (Permission permissionInner : permissionList) {
                userList = excludeExistUser(userList, permissionInner);
                if (userList.size() == 0) {
                    break;
                }
                userAuthorityMapper.batchAddUserAuthority(userList, permissionInner);
                Permission tempPermission = new Permission();
                tempPermission.setId(permissionInner.getId());
                tempPermission.setUserCount(permissionInner.getUserCount() + userList.size());
                permissionMapper.update(tempPermission);
            }
            return AjxResult.success("用户权限分配完成");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.toString());
            return AjxResult.unknownError("数据库操作异常");
        }
    }

    private List<User> excludeExistUser(List<User> userList, Permission permissionInner) {
        List<Long> existIdList = userAuthorityMapper.findUserIdsByAuthorityId(permissionInner.getId());
        ArrayList<User> tempUserList = new ArrayList<>();
        for (User user : userList) {
            if (!existIdList.contains(user.getId())) {
                tempUserList.add(user);
            }
        }
        return tempUserList;
    }

    @Transactional
    @Override
    public AjxResult removeUserPermission(RemoveUserPermissionVO removeUserPermissionVO) {
        if (removeUserPermissionVO == null || removeUserPermissionVO.getUserId() == null || removeUserPermissionVO.getPermissionId() == null) {
            return AjxResult.paramError("参数传入有误");
        }
        try {
            User user = new User();
            user.setId(removeUserPermissionVO.getUserId());
            User tempUser = userMapper.findOne(user);
            if (tempUser == null) {
                return AjxResult.paramError("用户不存在");
            }
            Permission tempPermission = permissionMapper.findById(removeUserPermissionVO.getPermissionId());
            if (tempPermission == null) {
                return AjxResult.paramError("权限不存在");
            }
            List<Permission> permissionList = MenuUtil.permissionRemoveListMerging(tempPermission, menuService);
            List<Long> permissionIncludeIdList = userAuthorityMapper.findAuthorityIdsByUserId(user.getId());
            permissionList = MenuUtil.extractIncludeRemove(permissionIncludeIdList, permissionList);
            for (Permission permissionInner : permissionList) {
                userAuthorityMapper.removeByUserIdAndPermissionId(user.getId(), permissionInner.getId());
                Permission permission = new Permission();
                permission.setId(permissionInner.getId());
                permission.setUserCount(permissionInner.getUserCount() - 1);
                permissionMapper.update(permission);
            }
            RedisUtil.deleteFold("caiden_micheal:user:" + removeUserPermissionVO.getUserId() + ":*");
            return AjxResult.success("移除成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjxResult.unknownError("数据库操作异常");
        }
    }

    @Transactional
    @Override
    public AjxResult addUser(UserAddVO userAddVO) {
        if (userAddVO == null || userAddVO.getUsername() == null || userAddVO.getEmail() == null || userAddVO.getDisabled() == null) {
            logger.warn(LoggerHead.warnHead() + "userAddVO: " + userAddVO);
            return AjxResult.paramError("参数传入有误");
        }
        User firstUser = userMapper.findByUsername(userAddVO.getUsername());
        if (firstUser != null) {
            logger.warn(LoggerHead.warnHead() + userAddVO.getUsername() + " Username Already exists!");
            return AjxResult.paramError("用户名已存在");
        }
        Org org;
        if (userAddVO.getOrgId() != null) {
            org = orgMapper.findById(userAddVO.getOrgId());
            if (org == null) {
                logger.warn(LoggerHead.warnHead() + userAddVO.getOrgId() + " OrgId non-existent!");
                return AjxResult.paramError("部门不存在");
            }
        } else {
            org = new Org();
        }
        User briefUser = new User();
        briefUser.setEmail(userAddVO.getEmail());
        firstUser = userMapper.findOne(briefUser);
        if (firstUser != null) {
            logger.warn(LoggerHead.warnHead() + userAddVO.getEmail() + " Email Registered!");
            return AjxResult.paramError("邮箱已注册");
        }
        try {
            User user = new User();
            BeanUtils.copyProperties(userAddVO, user);
            user.setOrgName(org.getOrgName());
            if (user.getPhone() != null) {
                user.setPhoneDesensitization(user.getPhone().substring(0, 3) + "****" + user.getPhone().substring(user.getPhone().length() - 4));
                user.setPhone(AESUtil.encrypt(user.getPhone(), aesProperties.getSecretKey()));
            }
            if (user.getWechat() != null) {
                user.setWechatDesensitization(user.getWechat().substring(0, 2) + "****" + user.getWechat().substring(user.getWechat().length() - 4));
                user.setWechat(AESUtil.encrypt(user.getWechat(), aesProperties.getSecretKey()));
            }
            if (user.getQq() != null) {
                user.setQqDesensitization(user.getQq().substring(0, 3) + "****" + user.getQq().substring(user.getQq().length() - 4));
                user.setQq(AESUtil.encrypt(user.getQq(), aesProperties.getSecretKey()));
            }
            user.setPassword(AESUtil.encrypt(aesProperties.getDefaultPwd(), aesProperties.getSecretKey()));
            int count = 0;
            String workNo;
            while (true) {
                if (count > 100) {
                    return AjxResult.unknownError("数据库已无可分配的工号，请修改workNo前缀后重启项目");
                }
                count++;
                workNo = WorkNoGenerateUtil.generateWorkNo(6);
                User tempUser = userMapper.findByWorkNO(workNo);
                if (tempUser == null) {
                    break;
                }
            }
            user.setWorkNo(workNo);
            userMapper.addUser(user);
            if (org.getId() != null) {
                Org tempOrg = new Org();
                tempOrg.setId(org.getId());
                tempOrg.setUserCount(org.getUserCount() + 1);
                orgMapper.update(tempOrg);
            }
            return AjxResult.success("添加成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjxResult.unknownError("数据库操作异常");
        }
    }

    @Override
    public AjxResult findUserDecryptDataById(Long userId) {
        if (userId == null) {
            return AjxResult.paramError("参数传入有误");
        }
        String encrypt;
        try {
            User user = new User();
            user.setId(userId);
            user = userMapper.findOne(user);
            if (user == null) {
                logger.warn(LoggerHead.warnHead() + userId + " userId non-existent!");
                return AjxResult.paramError("用户不存在");
            }
            DecryptDataDTO decryptDataDTO = new DecryptDataDTO();
            decryptDataDTO.setPhone(AESUtil.decrypt(user.getPhone(), aesProperties.getSecretKey()));
            decryptDataDTO.setWechat(AESUtil.decrypt(user.getWechat(), aesProperties.getSecretKey()));
            decryptDataDTO.setQq(AESUtil.decrypt(user.getQq(), aesProperties.getSecretKey()));
            encrypt = AESUtil.encrypt(JSON.toJSONString(decryptDataDTO), aesProperties.getSecretKey());
        } catch (Exception e) {
            logger.error(e.toString());
            return AjxResult.unknownError("数据库操作异常");
        }
        return AjxResult.success(encrypt);
    }

    @Transactional
    @Override
    public AjxResult editUser(UserEditVO userEditVO) {
        if (userEditVO == null || userEditVO.getId() == null || userEditVO.getEmail() == null || userEditVO.getDisabled() == null) {
            logger.warn(LoggerHead.warnHead() + "userEditVO: " + userEditVO);
            return AjxResult.paramError("参数传入有误");
        }
        User tempUser = new User();
        tempUser.setId(userEditVO.getId());
        User firstUser = userMapper.findOne(tempUser);
        if (firstUser == null) {
            logger.warn(LoggerHead.warnHead() + userEditVO.getId() + " UserId, User non-exists!");
            return AjxResult.paramError("用户不存在");
        }
        Org org;
        if (userEditVO.getOrgId() != null) {
            org = orgMapper.findById(userEditVO.getOrgId());
            if (org == null) {
                logger.warn(LoggerHead.warnHead() + userEditVO.getOrgId() + " OrgId non-existent!");
                return AjxResult.paramError("部门不存在");
            }
        } else {
            org = new Org();
        }
        User briefUser = new User();
        briefUser.setEmail(userEditVO.getEmail());
        User secondUser = userMapper.findOne(briefUser);
        if (secondUser != null && !Objects.equals(secondUser.getId(), userEditVO.getId())) {
            logger.warn(LoggerHead.warnHead() + userEditVO.getEmail() + " Email Registered!");
            return AjxResult.paramError("邮箱已注册");
        }
        try {
            User user = new User();
            BeanUtils.copyProperties(userEditVO, user);
            user.setOrgName(org.getOrgName());
            if (user.getPhone() != null) {
                user.setPhoneDesensitization(user.getPhone().substring(0, 3) + "****" + user.getPhone().substring(user.getPhone().length() - 4));
                user.setPhone(AESUtil.encrypt(user.getPhone(), aesProperties.getSecretKey()));
            }
            if (user.getWechat() != null) {
                user.setWechatDesensitization(user.getWechat().substring(0, 2) + "****" + user.getWechat().substring(user.getWechat().length() - 4));
                user.setWechat(AESUtil.encrypt(user.getWechat(), aesProperties.getSecretKey()));
            }
            if (user.getQq() != null) {
                user.setQqDesensitization(user.getQq().substring(0, 3) + "****" + user.getQq().substring(user.getQq().length() - 4));
                user.setQq(AESUtil.encrypt(user.getQq(), aesProperties.getSecretKey()));
            }
            user.setPassword(AESUtil.encrypt(aesProperties.getDefaultPwd(), aesProperties.getSecretKey()));
            userMapper.editUser(user);


            if (firstUser.getOrgId() != null && !Objects.equals(firstUser.getOrgId(), userEditVO.getOrgId())) {
                Org tempOrg = orgMapper.findById(firstUser.getOrgId());
                Org temp1 = new Org();
                temp1.setId(firstUser.getOrgId());
                temp1.setUserCount(tempOrg.getUserCount() - 1);
                orgMapper.update(temp1);
            }
            if (userEditVO.getOrgId() != null && !Objects.equals(firstUser.getOrgId(), userEditVO.getOrgId())) {
                Org tempOrg = orgMapper.findById(userEditVO.getOrgId());
                Org temp1 = new Org();
                temp1.setId(tempOrg.getId());
                temp1.setUserCount(tempOrg.getUserCount() + 1);
                orgMapper.update(temp1);
            }

            return AjxResult.success("修改成功");
        } catch (Exception e) {
            logger.error(e.toString());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjxResult.unknownError("数据库操作异常");
        }
    }

    @Transactional
    @Override
    public AjxResult userRemoveAuthority(RemoveUserPermissionVO removeUserPermissionVO) {
        if (removeUserPermissionVO == null || removeUserPermissionVO.getUserId() == null || removeUserPermissionVO.getPermissionId() == null) {
            logger.warn(LoggerHead.warnHead() + "removeUserPermissionVO: " + removeUserPermissionVO);
            return AjxResult.paramError("参数传入有误");
        }
        Permission permission = permissionMapper.findById(removeUserPermissionVO.getPermissionId());
        if (permission == null) {
            logger.warn(LoggerHead.warnHead() + removeUserPermissionVO.getPermissionId() + " permissionId, Permission non-exist!");
            return AjxResult.paramError("权限不存在");
        }
        User user = new User();
        user.setId(removeUserPermissionVO.getUserId());
        user = userMapper.findOne(user);
        if (user == null) {
            logger.warn(LoggerHead.warnHead() + removeUserPermissionVO.getUserId() + " UserId, User non-exist!");
            return AjxResult.paramError("用户不存在");
        }
        try {
            UserAuthority userAuthority = userAuthorityMapper.findByAuthorityIdAndUserId(removeUserPermissionVO.getPermissionId(), removeUserPermissionVO.getUserId());
            if (userAuthority == null) {
                return AjxResult.paramError("该权限是此用户的职位所在部门（或其职位本身或本人所在部门）所具有的权限，无法在此处移除");
            }
            List<Permission> permissionList = MenuUtil.permissionRemoveListMerging(permission, menuService);
            List<Long> permissionIncludeIdList = userAuthorityMapper.findAuthorityIdsByUserId(user.getId());
            permissionList = MenuUtil.extractIncludeRemove(permissionIncludeIdList, permissionList);
            for (Permission permissionInner : permissionList) {
                userAuthorityMapper.removeByUserIdAndPermissionId(user.getId(), permissionInner.getId());
                Permission tempPermission = new Permission();
                tempPermission.setId(permissionInner.getId());
                tempPermission.setUserCount(permissionInner.getUserCount() - 1);
                permissionMapper.update(tempPermission);
            }
            RedisUtil.deleteFold("caiden_micheal:user:" + removeUserPermissionVO.getUserId() + ":*");
            return AjxResult.success("用户本身所具有的【" + permission.getAuthorityName() + "】权限及其关联权限移除成功（注：若该权限还存在列表中说明与职位和部门有关，此处仅移除用户本身的该权限）");
        } catch (Exception e) {
            logger.error(e.toString());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjxResult.unknownError("数据库操作异常");
        }
    }

    @Transactional
    @Override
    public AjxResult userAddPermission(UserAddPermissionVO userAddPermissionVO) {
        if (userAddPermissionVO == null || userAddPermissionVO.getAuthorityIds() == null || userAddPermissionVO.getUserId() == null) {
            logger.warn(LoggerHead.warnHead() + "userAddPermissionVO: " + userAddPermissionVO);
            return AjxResult.paramError("参数传递有误");
        }
        User user = new User();
        user.setId(userAddPermissionVO.getUserId());
        user = userMapper.findOne(user);
        if (user == null) {
            logger.warn(LoggerHead.warnHead() + userAddPermissionVO.getUserId() + " userId, User non-exist!");
            return AjxResult.paramError("用户不存在");
        }
        List<Permission> permissionList = permissionMapper.findBatchByIds(userAddPermissionVO.getAuthorityIds());
        if (permissionList == null) {
            return AjxResult.paramError("权限均不存在");
        }
        try {
            MenuUtil.permissionListMerging(permissionList, menuService);
            List<Long> existsPermissionIdList = userAuthorityMapper.findAuthorityIdsByUserId(user.getId());
            permissionList = MenuUtil.excludeExistPermission(existsPermissionIdList, permissionList);
            userAuthorityMapper.batchAddByAuthorityListAndUser(permissionList, user);
            List<Long> permissionIdList = new ArrayList<>();
            for (Permission permission : permissionList) {
                permissionIdList.add(permission.getId());
            }
            permissionMapper.updateUserCountByIds(permissionIdList, true);
            return AjxResult.success("添加成功");
        } catch (Exception e) {
            logger.error(e.toString());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjxResult.unknownError("数据库操作异常");
        }
    }

    private void queryDataAndFillList(Long id, List<String> authorityNameList) {
        List<UserAuthority> userAuthorityList = userAuthorityMapper.findBatchAuthorityIdByUserId(id);
        List<UserAuthority> positionAuthorityList = positionService.findPositionAuthorityListByUserId(id);
        User user = new User();
        user.setId(id);
        user = userMapper.findOne(user);
        List<Long> orgIdList = positionOrgUserMapper.findOrgIdsByUserId(id);
        if (!orgIdList.contains(user.getOrgId())) {
            orgIdList.add(user.getOrgId());
        }
        List<UserAuthority> orgAuthorityList = orgService.findOrgAuthorityListByIds(orgIdList);
        List<UserAuthority> authorityList = new ArrayList<>();
        authorityList.addAll(userAuthorityList);
        authorityList.addAll(positionAuthorityList);
        authorityList.addAll(orgAuthorityList);
        ArrayList<String> tempAuthorityNameList = new ArrayList<>();
        for (UserAuthority userAuthority : authorityList) {
            tempAuthorityNameList.add(userAuthority.getAuthorityName());
        }
        authorityNameList.addAll(deduplicateList(tempAuthorityNameList));
    }

    public List<String> deduplicateList(List<String> list) {
        HashSet<String> set = new HashSet<>(list);
        return new ArrayList<>(set);
    }

    private Boolean deleteUserRelatedInformation(Long userId) {
        // TODO 用户删除抽取方法（等工作流都写完了才可以测试出来）
        // 需要放在一个事务里面
        // sys_org 人数-1
        // sys_position 人数-1
        // sys_position_org_user 删除
        // sys_user_authority 删除
        // sys_workflow_business 删除发起人为此用户的全部信息（未完成的信息）
        // sys_workflow_audit_info 删除对应的节点审核信息
        // sys_workflow_audit_info 将审核人为此人的节点需要更换（要求当前所在节点的进行人选择）
        // sys_user 删除
        return true;
    }
}
